import { deepClone, getRandomString } from "@/utils/utils";
import { ModuleType } from "@/type";

/**
 * 添加节点
 */
export function addNode(list: ModuleType[], targetId: string, module: ModuleType, index: number) {
  if (targetId) {
    list = list.map(item => {
      if (item.id === targetId && item.layout) {
        if (index > -1) {
          item.children.splice(index, 0, module);
        } else {
          item.children.push(module);
        }
      }
      if (item.children.length) {
        item.children = addNode(item.children, targetId, module, index);
      }
      return item;
    });
  } else {
    list.push(module);
  }
  return list;
}

/**
 * 复制节点
 */
export function copyNode(list: ModuleType[], targetId: string) {
  if (targetId) {
    const index = list.findIndex(node => node.id === targetId);
    if (index > -1) {
      list.splice(index, 0, updateNodeId(deepClone(list[index])));
    } else {
      list = list.map(node => {
        node.children = copyNode(node.children, targetId);
        return node;
      });
    }
    return list;
  }
  return list;
}

/**
 * 删除节点
 */
export function deleteNode(list: ModuleType[], targetId: string) {
  if (targetId) {
    list = list.filter(node => {
      if (node.id === targetId) {
        return false;
      }
      if (node.children.length) {
        node.children = deleteNode(node.children, targetId);
      }
      return true;
    });
    return list;
  }
  return list;
}

/**
 * 更新节点id
 */
export function updateNodeId(module: ModuleType) {
  module.id = getRandomString(5);
  // 内容补齐
  if (!module.children) {
    module.children = [];
  }
  if (!module.attribute) {
    module.attribute = [];
  }
  if (module.children && module.children.length) {
    module.children = module.children.map(node => {
      return updateNodeId(node);
    });
  }
  return module;
}

/**
 * 获取目标节点
 */
export function getTargetNode(list: ModuleType[], targetId: string) {
  if (list && list.length && targetId) {
    for (const node of list) {
      if (node.id === targetId) {
        return node;
      }
      if (node.children.length) {
        const targetNode = getTargetNode(node.children, targetId) as ModuleType;
        if (targetNode.id) {
          return targetNode;
        }
      }
    }
  }
  return {} as ModuleType;
}

/**
 * 获取节点属性
 */
export function getAttribute(node: ModuleType) {
  let attribute = "";
  if (node.attribute && node.attribute.length) {
    for (const item of node.attribute) {
      if (!item.value) {
        continue;
      }
      attribute += `${item.key}="${item.value}" `;
    }
  }
  if (attribute) {
    attribute = " " + attribute.substring(0, attribute.length - 1);
  }
  return attribute;
}
